<?php 
if (!defined('BASEPATH')){
	exit('No direct script access allowed');
}

/**
 * Adminlog Controller
 * Build by Phuc Nguyen
 * Contact : nguyenvanphuc0626@gmail.com
 */

class ListCustomers extends BACKEND_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->language('listcustomers');
		$this->load->language('button');
		if($this->database_connect_status){
			$this->load->model('listcustomers_model');
                        $this->load->model('user_model');
			$this->set_controller('listcustomers');
			$this->set_model($this->listcustomers_model);
		}
                $this->load->library('bookinglib');
                $this->bookinglib = new bookinglib();
	}
        
        public function detailCustomers(){
            $this->bookinglib->direct();
            $info                                           = $this->listcustomers_model->selectDetailCustomers($_GET['customerID']);
            
            
            $this->load->model('voucherLunisolar_model');
            $surplus            =   $this->voucherLunisolar_model->getSurByUserid($info[0]->customerID);
            $info[0]->surplus   =   $surplus[0]->residual + $info[0]->surplus;
            
            $this->view_data['phone']                       = implode(", ", json_decode($info[0]->phone));
            $this->view_data['info']                        = $info[0];
            $this->view_data['social']                      = json_decode($info[0]->social);
            
            $this->view_data['role_by_group'] 		= array();
		if($this->database_connect_status){
			$this->load->model('stats_model');
			$user_info = $this->stats_model->get_user_info($this->stats_model->get_user_id());
			$this->view_data['role_by_group'] = $user_info['role_list'];
			$this->view_data['username'] 	  = $user_info['username'];
                        $this->load->view('auth/listcustomers/view', $this->view_data);
                } else {
                        $this->view_data['flash_message']	= $this->lang->line('database_connect_failed');
                        $this->load->view('templates/backend/error', $this->view_data);	
                }            
        }

        protected function update($params=NULL){
		if($this->input->server('REQUEST_METHOD')=='POST'){
                        $social = array(
                            'email'         =>  $this->input->post('email'),
                            'yahoo'         =>  $this->input->post('yahoo'),
                            'skype'         =>  $this->input->post('skype'),
                            'facebook'      =>  $this->input->post('facebook')
                        );

                        $this->view_data["listcustomers"] 				= new stdClass();
                        $this->view_data["listcustomers"]->name                         = $this->input->post('name');
                        $this->view_data["listcustomers"]->type                         = $this->input->post('type');
                        $this->view_data["listcustomers"]->phone                        = ($this->input->post('phone'))?  json_encode($this->input->post('phone')):'';
                        $this->view_data["listcustomers"]->address                      = $this->input->post('address');
                        $this->view_data["listcustomers"]->province                     = ($this->input->post('province'))?$this->input->post('province'):'25';
                        $this->view_data["listcustomers"]->social                       = json_encode($social);
                        $this->view_data["listcustomers"]->birthday                     = ($this->input->post('birthday'))?date("Y-m-d", strtotime($this->input->post('birthday'))):'';
                        $this->view_data["listcustomers"]->member                       = $this->input->post('member');
                        $this->view_data["listcustomers"]->info_bill                    = $this->input->post('info_bill');
                        $this->view_data["listcustomers"]->note                         = $this->input->post('note');
                        $this->view_data["listcustomers"]->owner                        = $this->session->userdata['user_id'];
                        $this->view_data["listcustomers"]->share                        = json_encode(array($this->session->userdata['user_id']));
                        $this->view_data["listcustomers"]->salesID                      = $this->input->post('salesID');
                        
                        if($this->uri->segment(4) == "add"){
                            $this->view_data["listcustomers"]->lastupdated                  = time();
                        }
                        
			$this->load->helper('form');
			$this->load->helper('character');

			/**
			 * update list api phone sales
			*/
                        $this->load->model("sales_model");
                        $this->sales_model->deleteApiPhone($this->input->post('phone_fake'));
                        
                        $this->load->model('salesphone_model');
                        foreach($this->input->post('phone') as $k => $vls){
                            $exists = $this->salesphone_model->find_by(array('phone'=>$vls),'id,phone');
                            
                            $exis               =   new stdClass();
                            $exis->phone        =   $vls;
                            $exis->status       =   1;
                            $exis->waiting      =   0;
                            $exis->lastupdated  =   date("Y-m-d H:i:s");
                                
                            if($exists){
                                $this->salesphone_model->update($exis,$exists[0]->id);
                            } else {
                                $this->salesphone_model->create($exis);
                            }
                            unset($exists);
                            unset($exis);
                        }
			// Validate form.
			$this->load->helper('form');
			$this->load->library('form_validation');
			$this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
			//require field and xss clean
			$rules = array(
					array(
							'field'   => 'name',
							'label'   =>  $this->lang->line('name'),
							'rules'   => 'required|max_length[100]|xss_clean'
					),array(
							'field'   => 'phone',
							'label'   => $this->lang->line('phone'),
							'rules'   => 'required|max_length[255]|xss_clean'
					),array(
							'field'   => 'address',
							'label'   => $this->lang->line('address'),
							'rules'   => 'max_length[255]|xss_clean'
					),array(
							'field'   => 'province',
							'label'   => $this->lang->line('province'),
							'rules'   => 'max_length[100]|xss_clean'
					),array(
							'field'   => 'social',
							'label'   => $this->lang->line('social'),
							'rules'   => 'max_length[255]|xss_clean'
					),array(
							'field'   => 'birthday',
							'label'   => $this->lang->line('birthday'),
							'rules'   => 'xss_clean'
					),array(
							'field'   => 'member',
							'label'   => $this->lang->line('air_member'),
							'rules'   => 'xss_clean'
					),array(
							'field'   => 'info_bill',
							'label'   => $this->lang->line('info_bill'),
							'rules'   => 'max_length[1000]|xss_clean'
					),array(
							'field'   => 'note',
							'label'   => $this->lang->line('note'),
							'rules'   => 'max_length[255]|xss_clean'
					)
			);

			$this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
			$this->form_validation->set_rules($rules);

			if ($this->form_validation->run()==TRUE){
				if($params){
                                        //edit data
					$this->listcustomers_model->update($this->view_data["listcustomers"], $params,array('customerID' => $params));
					unset($this->view_data["listcustomers"]);
                                        $logAction                     = '[UpdateDSKH] '.$this->lang->line('update_listcustomers_success').$params;
                                        $customerID                    = $params;
				}else{
                                        $agent_code                                     = $this->listcustomers_model->getListAgentCode($this->session->userdata['agent_code']);
                                        $this->view_data["listcustomers"]->agent_code   = $this->session->userdata['agent_code'];
                                        $this->view_data["listcustomers"]->customerID   = $agent_code[1].$this->bookinglib->createCustomerID();
					$params                                         = $this->listcustomers_model->create($this->view_data["listcustomers"]);
                                        $params                                         = $this->listcustomers_model->find_by(array('id' => $params));
                                        $customerID                                     = $params[0]->customerID;
                                        $logAction                                      = '[AddDSKH] '.$this->lang->line('add_listcustomers_success').$customerID;
                                        //debug phuc nguyen
				}
                                
				if($customerID){
					$this->session->set_flashdata('flash_message', $this->lang->line('update_successful'));
					$paramAdminLog  = array(
                                            'userid'            => $this->session->userdata['user_id'],
                                            'lastLogin'         => date('Y-m-d :H:i:s',time()),
                                            'ip'                => $_SERVER['REMOTE_ADDR'],
                                            'logAction'         => $logAction,
                                            'agent_code'        => $this->session->userdata['agent_code']
                                        );
                                        $this->user_model->insertUserAdminLog($paramAdminLog);
                                        redirect('auth/booking');
				}
			}

		}
		$this->load->model('listcustomers_model');
		$this->load->model('language_model');

		if(isset($params)){
			$listcustomers_query	= $this->listcustomers_model->find_by(array('customerID' => $params));
			if(!isset($listcustomers_query[0])){
				$this->session->set_flashdata('flash_message', $this->lang->line('not_exists'));
				redirect(site_url('auth/listcustomers'));
				exit();
			}
                        
                        $listcustomers_query[0]->phone      = json_decode($listcustomers_query[0]->phone);
                        $social                             = json_decode($listcustomers_query[0]->social);

                        $listcustomers_query[0]->birthday   = ($listcustomers_query[0]->birthday != '0000-00-00')?date("d-m-Y", strtotime($listcustomers_query[0]->birthday)):'';
                        $listcustomers_query[0]->province   = $listcustomers_query[0]->province;
                        $listcustomers_query[0]->email      = (isset($social->email))?$social->email:'';
                        $listcustomers_query[0]->yahoo      = (isset($social->yahoo))?$social->yahoo:'';
                        $listcustomers_query[0]->skype      = (isset($social->skype))?$social->skype:'';;
                        $listcustomers_query[0]->facebook   = (isset($social->facebook))?$social->facebook:'';;
                        
			$this->view_data['listcustomers']				= $listcustomers_query[0];
		}
                
		$this->view_data['js'] = array(
				base_url().'static/templates/backend/js/main.js'
		);
		$this->view_data['css'] = array(
		);
		$this->load->view('auth/listcustomers/edit', $this->view_data);
	}
        
        private function menuTop(){
            $this->load->model('stats_model');
            $user_info                          = $this->stats_model->get_user_info($this->stats_model->get_user_id());
            $this->view_data['role_by_group']   = $user_info['role_list'];
            $this->view_data['username']        = $user_info['username'];
            return $this->view_data;
        }
        
        public function share(){
             $this->bookinglib->direct();
             $this->menuTop();
             if($this->input->server('REQUEST_METHOD')=='POST'){
                    $this->view_data["listcustomers"]                           = new stdClass();
                    $this->view_data["listcustomers"]->customerID               = $this->input->post('customerID');
                    $this->view_data["listcustomers"]->staff                    = $this->input->post('staff');
                    $this->view_data["listcustomers"]->lastupdated              = time();
                    
                    $this->load->helper('form');
                    $this->load->helper('character');
                    $this->load->helper('form');
                    $this->load->library('form_validation');
                    $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                    $rules = array(
                        array(
                            'field'   => 'staff',
                            'label'   =>  $this->lang->line('staff'),
                            'rules'   => 'required|trim|max_length[150]|xss_clean'
                        )
                    );

                    $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                    $this->form_validation->set_rules($rules);

                    if ($this->form_validation->run()==TRUE){
                        
                        $info                                                   = $this->listcustomers_model->find_by(array('customerID'=>$this->view_data["listcustomers"]->customerID));
                        $check                                                  = json_decode($info[0]->share);
                        $check[count($check)]                                   = $this->input->post('staff');
                        $contactshare                                           = array('share'=>  json_encode($check));
                        
                        //update contact share
                        $this->listcustomers_model->update($contactshare, '',array('customerID' => $this->view_data["listcustomers"]->customerID));
                        
                        $bookshare                                              = new stdClass();
                        $bookshare->customerID                                  = $this->input->post('customerID');
                        $bookshare->receive_id                                  = $this->input->post('staff');
                        $bookshare->share_id                                    = $this->session->userdata['user_id'];
                        $bookshare->lastupdated                                 = time();
                        
                        $this->load->model('bookshare_model');
                        $params                                                 = $this->bookshare_model->create($bookshare);
                        if(!$params){
                            echo $this->lang->line("db_fail");die();
                        }                        
                        if($params){
                                $this->session->set_flashdata('flash_message', $this->lang->line('update_successful'));
                                $paramAdminLog  = array(
                                    'userid'            => $this->session->userdata['user_id'],
                                    'lastLogin'         => date('Y-m-d :H:i:s',time()),
                                    'ip'                => $_SERVER['REMOTE_ADDR'],
                                    'logAction'         => 'user_id='.$bookshare->share_id.' chia sẻ KH('.$bookshare->customerID.') cho user_id = '.$bookshare->receive_id .' thành công',
                                    'agent_code'        => $this->session->userdata['agent_code']
                                );
                                $this->user_model->insertUserAdminLog($paramAdminLog);               
                                unset($contactshare);
                                unset($bookshare);
                                redirect('auth/listcustomers/');
                        }
                    }
                    
             } else {
                 $share                           = $this->listcustomers_model->find_by(array('customerID'=>$this->input->get("customerID")));
                $this->view_data['share']        = $share[0];
                $this->load->view('auth/listcustomers/share', $this->view_data);
             }
        }
        
        public function search(){
            $this->view_data                = array();
            $this->view_data['info']        = '';
            if($this->input->server('REQUEST_METHOD')=='POST'){
                $params = array(
                    'name'          =>  $this->input->post('name'),
                    'phone'         =>  $this->input->post('phone')
                );
                
                $this->view_data['info']     =   $this->listcustomers_model->searchCustomers($params['name'],$params['phone']);
                if(empty($this->view_data['info'])){
					die("Khong tim thay du lieu KH");
				} else {
					$this->load->view('auth/listcustomers/search', $this->view_data);
					die("");
				}
            }
            
            $this->view_data['flash_message_error']         = $this->session->flashdata('flash_message_error');
            $this->view_data['flash_message']		= $this->session->flashdata('flash_message');

            if($this->database_connect_status){
                    $this->menuTop();
                    $this->load->view('auth/listcustomers/search', $this->view_data);
            } else {
                    $this->view_data['flash_message']	= $this->lang->line('database_connect_failed');
                    $this->load->view('templates/backend/error', $this->view_data);	
            }
        }
}